﻿using Fiddler;
using LOLBattleQuery.Do;
using Microsoft.Win32;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using static LOLBattleQuery.Do.GetBattleReportResult;
using static LOLBattleQuery.Do.LcuMatchHistoryProductsResult;
using static LOLBattleQuery.Do.SgpMatchHistoryQuery;
using static LOLBattleQuery.Program;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace LOLBattleQuery
{
    internal class Program
    {
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }

        private static bool Handler(CtrlType sig)
        {
            if (FiddlerApplication.IsStarted())
            {
                Info("Shutdown Fiddler");
                FiddlerApplication.Shutdown();
            }
            DisableFiddlerProxy();
            Info("Exit");
            Environment.Exit(-1);
            return true;
        }
        #endregion

        public static bool queryMvp { get; set; } = true;

        public static bool DisableFiddlerProxy()
        {
            using (RegistryKey regKey = Registry.CurrentUser)
            {
                string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
                RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);             //更改健值，设置代理
                if (optionKey.GetValue("ProxyEnable")?.ToString() == "1")
                {
                    string v = optionKey.GetValue("ProxyServer")?.ToString();

                    optionKey.SetValue("ProxyEnable", 0);

                }
                InternetSetOption(0, 39, IntPtr.Zero, 0);
                InternetSetOption(0, 37, IntPtr.Zero, 0);
                regKey.Flush();
            }
            return false;
        }

        [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto,
   EntryPoint = "InternetSetOption",
   CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption(
 int hInternet, int dmOption, IntPtr lpBuffer, int dwBufferLength);


        #region 关闭控制台 快速编辑模式、插入模式
        const int STD_INPUT_HANDLE = -10;
        const uint ENABLE_QUICK_EDIT_MODE = 0x0040;
        const uint ENABLE_INSERT_MODE = 0x0020;
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr GetStdHandle(int hConsoleHandle);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);

        public static void DisbleQuickEditMode()
        {
            IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);
            uint mode;
            GetConsoleMode(hStdin, out mode);
            mode &= ~ENABLE_QUICK_EDIT_MODE;//移除快速编辑模式
            mode &= ~ENABLE_INSERT_MODE;      //移除插入模式
            SetConsoleMode(hStdin, mode);
        }
        #endregion


        public static bool FirstOpenFildder { get; set; } = true;

        public static void OpenFiddler()
        {
            if (FirstOpenFildder)
            {
                FirstOpenFildder = false;
                try
                {
                    InstallCertificate();
                }
                catch (CryptographicException ex)
                {
                    Error("本程序需要使用管理员权限才可正常运行！");
                    Info("按下任意键程序将关闭");
                    Console.ReadKey();
                    Environment.Exit(0);
                }
                //CONFIG.bStreamAudioVideo = true;
            }
            var port = new Random().Next(20000, 21000);
            FiddlerApplication.Startup(port, true, true, true);
            FiddlerApplication.FiddlerDetach += FiddlerApplication_FiddlerDetach;
            Info("Startup -> " + port);
            FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeRespone;
            FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
            Info("Listen Event");
        }

        public static Config config { get; set; }

        public static void LoadConfig()
        {
            var application = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string path = application + "\\LOLBattleQuery\\config.json";
            var file = new FileInfo(path);
            if (!file.Directory.Exists)
            {
                file.Directory.Create();
                Info("Create Config Directory->" + file.Directory.FullName);
            }
            if (file.Exists)
            {
                Info("Load Config File -> " + file.FullName);
                config = File.ReadAllText(file.FullName, Encoding.UTF8).JsonDeserialize<Config>();
                if (config == null)
                {
                    Info("Error Config File -> " + file.FullName);
                    config = new Config();
                    SaveConfig();
                }
                if (config.SgpHosts == null)
                {
                    config.SgpHosts = GetDefaultSgpHost();
                    SaveConfig();
                }
            }
            else
            {
                config = new Config();
                config.SgpHosts = GetDefaultSgpHost();
                SaveConfig();
            }
            LCUHttpHelper.SgpHosts = config.SgpHosts;
        }

        private static Dictionary<string, string> GetDefaultSgpHost()
        {
            return new Dictionary<int, string>() {
               { 1, "hn1-cloud-sgp.lol.qq.com:21019" },
               { 2, "wt1new-sgp.lol.qq.com:21019" },
               { 3, "hn2-cloud-sgp.lol.qq.com:21019" },
               { 4, "hn3-cloud-sgp.lol.qq.com:21019" },
               { 5, "hn4new-sgp.lol.qq.com:21019" },
               { 6, "wt2new-sgp.lol.qq.com:21019" },
               { 7, "hn5-sgp.lol.qq.com:21019" },
               { 8, "hn6-sgp.lol.qq.com:21019" },
               { 9, "wt3new-sgp.lol.qq.com:21019" },
               { 10, "hn7-sgp.lol.qq.com:21019" },
               { 11, "hn8-cloud-sgp.lol.qq.com:21019" },
               { 12, "wt4new-sgp.lol.qq.com:21019" },
               { 13, "hn9-sgp.lol.qq.com:21019" },
               { 14, "hn10-cloud-sgp.lol.qq.com:21019" },
               { 15, "hn11-cloud-sgp.lol.qq.com:21019" },
               { 16, "wt5-sgp.lol.qq.com:21019" },
               { 17, "hn12-sgp.lol.qq.com:21019" },
               { 18, "hn13-cloud-sgp.lol.qq.com:21019" },
               { 19, "hn14new-sgp.lol.qq.com:21019" },
               { 20, "wt6-sgp.lol.qq.com:21019" },
               { 21, "edu1-sgp.lol.qq.com:21019" },
               { 22, "hn15-cloud-sgp.lol.qq.com:21019" },
               { 23, "hn16-cloud-sgp.lol.qq.com:21019" },
               { 24, "hn17-cloud-sgp.lol.qq.com:21019" },
               { 25, "hn18-cloud-sgp.lol.qq.com:21019" },
               { 26, "wt7-sgp.lol.qq.com:21019" },
               { 27, "hn19-sgp.lol.qq.com:21019" },
               { 30, "bgp1-sgp.lol.qq.com:21019" },
               { 31, "bgp2-sgp.lol.qq.com:21019" },
               { 999, "jp-red.lol.sgp.pvp.net" },
               { 1000,"tw2-red.lol.sgp.pvp.net" },
               { 1001,"sg2-red.lol.sgp.pvp.net" },
               { 1002, "kr-red.lol.sgp.pvp.net" },
               { 1003, "na-red.lol.sgp.pvp.net" },
               { 1004, "pbe-red.lol.sgp.pvp.net" },
               { 1005, "vn2-red.lol.sgp.pvp.net" },
            }.ToDictionary(x=>x.Key.ToString(),x=>x.Value);
        }

        public static void SaveConfig()
        {
            var application = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string path = application + "\\LOLBattleQuery\\config.json";
            File.WriteAllText(path, config.JsonSerialize());
            //Info("Save Config File -> " + path);
        }




        public class Class1
        {
            public Info2 info { get; set; }
            public Rewardgroup rewardGroup { get; set; }
        }

        public class Info2
        {
            public DateTime dateCreated { get; set; }
            public object[] grantElements { get; set; }
            public string granteeId { get; set; }
            public Grantordescription grantorDescription { get; set; }
            public string id { get; set; }
            public Messageparameters messageParameters { get; set; }
            public string rewardGroupId { get; set; }
            public object[] selectedIds { get; set; }
            public string status { get; set; }
            public bool viewed { get; set; }
        }

        public class Grantordescription
        {
            public string appName { get; set; }
            public string entityId { get; set; }
        }

        public class Messageparameters
        {
        }

        public class Rewardgroup
        {
            public bool active { get; set; }
            public string celebrationType { get; set; }
            public object[] childRewardGroupIds { get; set; }
            public string id { get; set; }
            public Localizations localizations { get; set; }
            public Media media { get; set; }
            public string productId { get; set; }
            public string rewardStrategy { get; set; }
            public Reward[] rewards { get; set; }
            public Selectionstrategyconfig selectionStrategyConfig { get; set; }
            public object[] types { get; set; }
        }

        public class Localizations
        {
            public string description { get; set; }
            public string title { get; set; }
        }

        public class Media
        {
        }

        public class Selectionstrategyconfig
        {
            public int maxSelectionsAllowed { get; set; }
            public int minSelectionsAllowed { get; set; }
        }

        public class Reward
        {
            public string fulfillmentSource { get; set; }
            public string id { get; set; }
            public string itemId { get; set; }
            public string itemType { get; set; }
            public Localizations1 localizations { get; set; }
            public Media1 media { get; set; }
            public int quantity { get; set; }
        }

        public class Localizations1
        {
            public string details { get; set; }
            public string title { get; set; }
        }

        public class Media1
        {
            public string iconUrl { get; set; }
        }


        static string Encode(long inp, IEnumerable<char> map)
        {
            var b = map.Count();
            var toChar = map.Select((v, i) => new { Value = v, Index = i }).ToDictionary(i => i.Index, i => i.Value);
            var res = "";
            if (inp == 0)
            {
                return "" + toChar[0];
            }
            while (inp > 0)
            {
                var val = (int)(inp % b);
                inp = inp / b;
                res += toChar[val];
            }
            return res;
        }




        static void Main(string[] args)
        {
            try
            {
                Console.InputEncoding = Encoding.Unicode;
                Console.OutputEncoding = Encoding.Unicode;
                DisableFiddlerProxy();
                if (FiddlerApplication.IsStarted())
                {
                    FiddlerApplication.Shutdown();
                }
                _handler += new EventHandler(Handler);
                SetConsoleCtrlHandler(_handler, true);
                Console.WriteLine("db       .d88b.  db      d8888b.  .d8b.  d888888b d888888b db      d88888b  .d88b.  db    db d88888b d8888b. db    db \r\n88      .8P  Y8. 88      88  `8D d8' `8b `~~88~~' `~~88~~' 88      88'     .8P  Y8. 88    88 88'     88  `8D `8b  d8' \r\n88      88    88 88      88oooY' 88ooo88    88       88    88      88ooooo 88    88 88    88 88ooooo 88oobY'  `8bd8'  \r\n88      88    88 88      88~~~b. 88~~~88    88       88    88      88~~~~~ 88    88 88    88 88~~~~~ 88`8b      88    \r\n88booo. `8b  d8' 88booo. 88   8D 88   88    88       88    88booo. 88.     `8P  d8' 88b  d88 88.     88 `88.    88    \r\nY88888P  `Y88P'  Y88888P Y8888P' YP   YP    YP       YP    Y88888P Y88888P  `Y88'Y8 ~Y8888P' Y88888P 88   YD    YP    \r\n                                                                                                                      ");
                Info("SetConsoleCtrlHandler");
                DisbleQuickEditMode();
                Info("DisbleQuickEditMode");
                Info("Author -> @初夏");
                Info("Video UP -> @慎ninja(抖音、B站)");
                Info("Bug Report -> QQ群:801977381");
                Info("Version -> 1.0.2 (2023-08-17 21:45:54)");
                LoadConfig();
                if (args.Length == 1 && args[0].EndsWith(".rofl"))
                {
                    if (string.IsNullOrWhiteSpace(config.GamePath))
                    {
                        Error("至少需要启动过一次游戏,才可拖入回放文件到本程序打开回放！");
                        Info("按下任意键程序退出");
                        Console.ReadKey();
                        Environment.Exit(0);
                        return;
                    }
                    WatchRofl(args[0], config.GamePath, config.WorkingDirectory);
                    Info("按下任意键程序退出");
                    Console.ReadKey();
                    Environment.Exit(0);
                }
                Info("Tip -> 使用 /? 或者 /help 命令查看指令大全");
                lcu = new LCUHttpHelper();
                bool tmp = false;
                Task.Run(() =>
                {
                    try
                    {
                        while (true)
                        {
                            try
                            {
                                if (!tmp)
                                {
                                    lcu = new LCUHttpHelper();
                                }
                                if (tmp == lcu.connect)
                                {
                                    continue;
                                }
                                else
                                {
                                    tmp = lcu.connect;
                                    Console.WriteLine();
                                    Info("LeagueClientUx Connect -> " + lcu.connect);
                                }
                                if (tmp)
                                {
                                    Info("LeagueClientUx Port -> " + lcu.http.BaseAddress.Port);
                                    while (true)
                                    {
                                        try
                                        {
                                            var content = lcu.GetAsync("/lol-rso-auth/v1/authorization").Result;
                                            var auth = content.Content.ReadAsStringAsync().Result.JsonDeserialize<LcuAuthorization>();
                                            if (area != auth.area)
                                            {
                                                openid = new Dictionary<string, string>();
                                                player = new Dictionary<string, LcuSummons>();
                                            }
                                            area = auth.area;
                                            currentPlatformId = auth.currentPlatformId;
                                            config.GamePath = lcu.GamePath;
                                            config.WorkingDirectory = lcu.WorkingDirectory;
                                            SaveConfig();
                                            if (auth.area < 100)
                                            {
                                                Info("当前登录大区：" + LcuAuthorization.GetArea(auth.area) + "，可以进行隐藏查询");
                                            }
                                            else
                                            {
                                                Info("当前登录服务器：" + LcuAuthorization.GetArea(auth.area));
                                            }
                                            Info("Input Command -> ", false);

                                            if (config.BattleQuery)
                                            {
                                                OpenFiddler();
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            Thread.Sleep(1000);
                                        }
                                    }
                                }
                                else
                                {
                                    if (config.BattleQuery)
                                    {
                                        CloseFiddler();
                                    }
                                }
                                Thread.Sleep(100);
                                continue;

                            }
                            catch (Exception ex)
                            {
                                if (ex is ManagementException)
                                {
                                    Error("Windows系统组件损坏，请在使用管理员权限在CMD执行以下命令(命令已自动复制)");
                                    Error("mofcomp %windir%\\system32\\wbem\\cimwin32.mof");
                                    Error("mofcomp %windir%\\system32\\wbem\\cimwin32.mfl");
                                    SetText("mofcomp %windir%\\system32\\wbem\\cimwin32.mof\r\nmofcomp %windir%\\system32\\wbem\\cimwin32.mfl");
                                    Info("程序将在 10 秒后关闭");
                                    Thread.Sleep(10 * 1000);
                                    Environment.Exit(0);
                                }
                                else
                                {
                                    Error("出现异常:" + ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                });
                while (true)
                {
                    Info("Input Command -> ", false);
                    var input = Console.ReadLine();
                    if (input.TrimStart().StartsWith("/?") || input.TrimStart().StartsWith("/help"))
                    {
                        Info("--------------------------------- LOLBattleQuery Help --------------------------------- ");
                        Info("/战绩\t\t\t\t\t\t" + (config.BattleQuery ? "关闭" : "开启") + "WeGame隐藏战绩查询功能");
                        Info("/令牌\t\t\t\t\t\t查看游戏登录令牌");
                        Info("/清屏\t\t\t\t\t\t清空控制台显示信息");
                        Info("/领奖\t\t\t\t\t\t领取所有可领取的奖励(可用于斗魂武道大会,声望达标即可领取)");
                        Info("/观战 <大区:文本/默认本区(服)> <玩家名称:文本>\t对该玩家进行观战");
                        Info("/回放 <回放路径:文本>\t\t\t\t打开指定回放文件");
                        Info("/跳关 <关卡:数字/0-20>\t\t\t\t将斗魂武道大会的关卡设置为指定关卡");
                        Info("/取消代理\t\t\t\t\t取消本机代理(出现断网时,建议使用该命令)");
                        Info("/对局分析\t\t\t\t\t获取对局分析指令(用于自定义/人机/云顶/斗魂等模式)");
                        Info("--------------------------------- LOLBattleQuery Help --------------------------------- ");
                    }
                    else if (input.TrimStart().ToLower().StartsWith("/清屏"))
                    {
                        Console.Clear();
                        Info("显示信息清理完毕");
                    }
                    else if (input.TrimStart().ToLower().StartsWith("/回放"))
                    {
                        input = input.TrimStart().Substring(3).TrimStart().TrimEnd();
                        var inputArgs = input.Split(' ');
                        if (inputArgs.Length == 0)
                        {
                            Error("请输入正确的指令，/回放 <回放路径:文本>");
                            continue;
                        }
                        else
                        {
                            WatchRofl(input, lcu.GamePath, lcu.WorkingDirectory);
                        }
                    }
                    else if (input.TrimStart().ToLower().StartsWith("/令牌"))
                    {
                        if (!lcu.connect)
                        {
                            Error("请启动游戏客户端！");
                        }
                        else
                        {
                            string token = GetAccessToken();
                            Info(token);
                            SetText(token);
                            Info("令牌已自动复制");
                        }
                    }
                    else if (input.TrimStart().StartsWith("/跳关"))
                    {
                        input = input.TrimStart().Substring(3).TrimStart().TrimEnd();
                        var inputArgs = input.Split(' ');
                        if (int.TryParse(inputArgs[0], out int gq))
                        {
                            var json = lcu.PostAsync("/lol-marketing-preferences/v1/partition/sfm2023", new
                            {
                                progress = inputArgs[0]
                            }.JsonSerialize()).Result.Content.ReadAsStringAsync().Result;
                            Info("已将关卡修改置 -> " + inputArgs[0] + "关！");
                        }
                        else
                        {
                            Error("请输入正确的关卡！");
                        }
                    }
                    else if (input.TrimStart().StartsWith("/领奖"))
                    {
                        var json = lcu.GetAsync("/lol-rewards/v1/grants").Result.Content.ReadAsStringAsync().Result;
                        var root = json.JsonDeserialize<List<Class1>>();
                        if (!root.Any())
                        {
                            Info("当前账号没有可领取的奖励！");
                        }
                        else
                        {
                            foreach (var item in root.OrderBy(x => x.info.dateCreated))
                            {
                                foreach (var item2 in item.rewardGroup.rewards)
                                {
                                    if (!string.IsNullOrWhiteSpace(item2.localizations.details) || item.info.status == "FULFILLED")
                                    {
                                        Error("奖励:" + item2.localizations.title + " -> " + item2.localizations.details);
                                    }
                                    else
                                    {
                                        var post = lcu.PostAsync("/lol-rewards/v1/grants/" + item.info.id + "/select", new
                                        {
                                            grantId = item.info.id,
                                            rewardGroupId = item.info.rewardGroupId,
                                            selections = new List<object>() { item2.id }
                                        }.JsonSerialize()).Result.Content.ReadAsStringAsync().Result;
                                        if (post.Contains("errorCode"))
                                        {
                                            Console.WriteLine(post);
                                        }
                                        else
                                        {
                                            Info("奖励:" + item2.localizations.title + " -> 执行领取！");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (input.TrimStart().StartsWith("/取消代理"))
                    {
                        if (FiddlerApplication.IsStarted())
                        {
                            FiddlerApplication.Shutdown();
                        }
                        DisableFiddlerProxy();
                        Info("代理已取消！");
                    }
                    else if (input.TrimStart().StartsWith("/战绩"))
                    {
                        config.BattleQuery = !config.BattleQuery;
                        SaveConfig();
                        Info(config.BattleQuery ? "战绩查询已开启" : "战绩查询已关闭");
                        if (config.BattleQuery)
                        {
                            OpenFiddler();
                        }
                        else
                        {
                            CloseFiddler();
                        }
                    }
                    else if (input.TrimStart().StartsWith("/对局分析"))
                    {
                        var web = new WebClient();
                        web.Encoding = Encoding.UTF8;
                        var tk = GetAccessToken();
                        char[] padding = { '=' };
                        string s = tk.Split('.')[1];
                        s = s.Replace('_', '/').Replace('-', '+');
                        switch (s.Length % 4)
                        {
                            case 2: s += "=="; break;
                            case 3: s += "="; break;
                        }
                        var puuid = Encoding.UTF8.GetString(Convert.FromBase64String(s)).JsonDeserialize<Dictionary<string, object>>()["sub"];
                        web.Headers.Add("Authorization", "Bearer " + tk);
                        web.Headers.Add("Content-Type", "application/json");
                        var content = string.Empty;
                        try
                        {
                            content = web.DownloadString("https://" + lcu.GetSgp(area) + "/gsm/v1/ledge/region/" + lcu.GetRegion(area) + "/puuid/" + puuid);
                        }
                        catch (WebException webex)
                        {
                            using (var stream = new StreamReader(webex.Response.GetResponseStream()))
                            {
                                content = stream.ReadToEnd();
                            }
                        }
                        if (content.Contains("Player was not found"))
                        {
                            Error("当前不在对局中!");
                        }
                        else
                        {
                            var obj = content.JsonDeserialize<Dictionary<string, object>>();
                            var game = obj["game"] as Dictionary<string, object>;
                            var map = new char[] {
                                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
                                'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                                'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                                'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't',
                                'u', 'v', 'x', 'y', 'z', '2', '3', '4',
                            };
                            var cmd = "/对局分析 " + Encode(long.Parse(area + "00" + game["id"]), map);
                            Info("指令 -> " + cmd);
                            SetText(cmd);
                            Info("对局分析指令已自动复制,将指令发送到群即可进行对局分析！");
                        }
                    }
                    else if (input.TrimStart().StartsWith("/观战"))
                    {
                        try
                        {
                            int sarea = area;
                            string name = string.Empty;
                            var inputArgs = new string[0];
                            if (area < 100)
                            {
                                input = input.TrimStart().Substring(3).TrimStart().TrimEnd();
                                inputArgs = input.Split(' ');
                                if (inputArgs.Length == 0)
                                {
                                    Error("请输入正确的指令，/观战 <大区:文本/默认本区(服)> <玩家名称:文本>");
                                    continue;
                                }
                                else if (inputArgs.Length != 1)
                                {
                                    sarea = LcuAuthorization.GetArea(inputArgs[0]);
                                    name = inputArgs[1];
                                }
                                else
                                {
                                    name = input;
                                }
                            }
                            else
                            {
                                name = input;
                            }
                            if (sarea == -1)
                            {
                                if (inputArgs.Length != 1)
                                {
                                    Error("未知大区:" + inputArgs[0]);
                                }
                                else
                                {
                                    Error("当前服务器:" + currentPlatformId + "，暂不支持使用该功能");
                                }
                            }
                            else
                            {
                                if (!lcu.connect)
                                {
                                    Error("请启动游戏客户端！");
                                }
                                else
                                {
                                    WebClient web = new WebClient();
                                    var content = string.Empty;
                                    try
                                    {
                                        web.Encoding = Encoding.UTF8;
                                        web.Headers.Add("Authorization", "Bearer " + GetAccessToken());
                                        web.Headers.Add("Content-Type", "application/json");
                                        content = web.DownloadString("https://" + lcu.GetSgp(sarea) + "/summoner-ledge/v1/regions/" + lcu.GetRegion(sarea) + "/summoners/name/" + name);
                                    }
                                    catch (WebException webex)
                                    {
                                        using (var stream = new StreamReader(webex.Response.GetResponseStream()))
                                        {
                                            content = stream.ReadToEnd();
                                        }
                                    }
                                    if (content.Contains("summoner not found"))
                                    {
                                        Error("找不到召唤师：" + name);
                                    }
                                    else if(content.Contains("504 Gateway"))
                                    {
                                        Error("当前大区Sgp地址已失效，当前地址 -> " + lcu.GetSgp(sarea));
                                    }
                                    else
                                    {
                                        var obj = content.JsonDeserialize<Dictionary<string, object>>();
                                        try
                                        {
                                            web = new WebClient();
                                            web.Encoding = Encoding.UTF8;
                                            web.Headers.Add("Authorization", "Bearer " + GetAccessToken());
                                            web.Headers.Add("Content-Type", "application/json");
                                            content = web.DownloadString("https://" + lcu.GetSgp(sarea) + "/gsm/v1/ledge/spectator/region/" + lcu.GetRegion(sarea) + "/puuid/" + obj["puuid"]);
                                        }
                                        catch (WebException webex)
                                        {
                                            using (var stream = new StreamReader(webex.Response.GetResponseStream()))
                                            {
                                                content = stream.ReadToEnd();
                                            }
                                        }
                                        if (content.Contains("Game is not able to be spectated"))
                                        {
                                            Error("该模式不支持观战!");
                                        }
                                        else if (content.Contains("Player was not found"))
                                        {
                                            Error("玩家当前不在对局中!");
                                        }
                                        else
                                        {
                                            obj = content.JsonDeserialize<Dictionary<string, object>>();
                                            var playerCredentials = obj["playerCredentials"] as Dictionary<string, object>;
                                            var gameCreateDate = ToDateTime(Int64.Parse(playerCredentials["gameCreateDate"].ToString()));
                                            var time = DateTime.Now - gameCreateDate;
                                            if (time.TotalSeconds < 185)
                                            {
                                                Info("玩家对局未到三分钟,还需等待" + (185 - (int)time.TotalSeconds) + "秒才能观战,是否继续观战");
                                                Info("Y = 继续观战");
                                                Info("按下任意键 = 取消观战");
                                                var key = Console.ReadKey(true);
                                                if (key.Key == ConsoleKey.Y)
                                                {
                                                    int Seconds = 185 - (int)(DateTime.Now - gameCreateDate).TotalSeconds;
                                                    Info("执行等待" + (int)Seconds + "秒");
                                                    Thread.Sleep(Seconds * 1000);
                                                    Spectator(sarea, playerCredentials);
                                                }
                                                else
                                                {
                                                    Info("观战已取消!");
                                                }
                                            }
                                            else
                                            {
                                                Spectator(sarea, playerCredentials);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Error(ex.ToString());
                        }
                    }
                    else if (input.TrimStart().StartsWith("/取消观战"))
                    {
                        var result = lcu.PostAsync("/lol-lobby/v1/lobby/custom/cancel-champ-select", "");
                        if (result.Result.StatusCode == HttpStatusCode.NoContent)
                        {
                            Info("已取消");
                        }
                        else
                        {
                            Error("取消失败");
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(input))
                        {
                            continue;
                        }
                        Error("未知的命令 \"" + input + "\"");
                    }
                }
            }
            catch (Exception ex)
            {
                Error(ex.ToString());
                Error("出现异常,按下任意键程序退出!");
                Console.ReadKey();
                FiddlerApplication.Shutdown();
                DisableFiddlerProxy();
            }
        }

        private static void CloseFiddler()
        {
            FiddlerApplication.BeforeResponse -= FiddlerApplication_BeforeRespone;
            FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
            FiddlerApplication.Shutdown();
            Info("UnListen Event");
        }

        [DllImport("User32")]
        internal static extern bool OpenClipboard(IntPtr hWndNewOwner);

        [DllImport("User32")]
        internal static extern bool CloseClipboard();

        [DllImport("User32")]
        internal static extern bool EmptyClipboard();

        [DllImport("User32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SetClipboardData(int uFormat, IntPtr hMem);

        internal static void SetText(string text)
        {
            if (!OpenClipboard(IntPtr.Zero))
            {
                SetText(text);
                return;
            }
            EmptyClipboard();
            SetClipboardData(13, Marshal.StringToHGlobalUni(text));
            CloseClipboard();
        }

        private static void Spectator(int sarea, Dictionary<string, object> playerCredentials)
        {
            List<string> cmdArgs = new List<string>();
            List<object> spectator = new List<object>
            {
                "spectator",
                playerCredentials["observerServerIp"] + ":" + playerCredentials["observerServerPort"],
                playerCredentials["observerEncryptionKey"],
                playerCredentials["gameId"],
                lcu.GetRegion(sarea)
            };
            cmdArgs.Add(string.Join(" ", spectator));
            cmdArgs.Add("-Locale=zh_CN");
            cmdArgs.Add("-GameBaseDir=" + lcu.WorkingDirectory);
            new Process()
            {
                StartInfo = {
                   FileName = lcu.GamePath,
                   Arguments = string.Join(" ",cmdArgs.Select(x => "\"" + x + "\"")),
                   WorkingDirectory = lcu.WorkingDirectory
               }
            }.Start();
            Info("观战已唤起!");
        }

        private static void WatchRofl(string roflPath, string GamePath, string WorkingDirectory)
        {
            if (!File.Exists(roflPath))
            {
                Error("回放文件不存在!");
                return;
            }
            var bs = File.ReadAllBytes(roflPath).ToList();
            var txt = Encoding.UTF8.GetString(bs.GetRange(300, 100).ToArray());
            string version = Regex.Match(txt, "\"gameVersion\":\"(.*?)\"").Groups[1].Value;
            var fi = new FileInfo(roflPath);
            System.Diagnostics.FileVersionInfo file1 = System.Diagnostics.FileVersionInfo.GetVersionInfo(GamePath);
            var FileVersions = file1.FileVersion;
            var v1 = new Version(version);
            var v2 = new Version(FileVersions);
            if (v1.Major == v2.Major && v1.Minor == v2.Minor && v1.Build == v2.Build)
            {
                List<string> cmdArgs = new List<string>();
                cmdArgs.Add(roflPath);
                cmdArgs.Add("-Locale=zh_CN");
                cmdArgs.Add("-GameBaseDir=" + WorkingDirectory);
                new Process()
                {
                    StartInfo = {
                       FileName = GamePath,
                       Arguments = string.Join(" ",cmdArgs.Select(x => "\"" + x + "\"")),
                       WorkingDirectory = WorkingDirectory
                    }
                }.Start();
                Info("回放文件已唤起!");
                //Error("回放文件不存在!");
                //return;
            }
            else
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + v1.Major + "." + v1.Minor + "." + v1.Build + "\\League of Legends.exe";
                if (File.Exists(path))
                {
                    var fi2 = new FileInfo(path);
                    List<string> cmdArgs = new List<string>();
                    cmdArgs.Add(roflPath);
                    cmdArgs.Add("-Locale=zh_CN");
                    cmdArgs.Add("-GameBaseDir=" + WorkingDirectory);
                    new Process()
                    {
                        StartInfo = {
                           FileName = path,
                           Arguments = string.Join(" ",cmdArgs.Select(x => "\"" + x + "\"")),
                           WorkingDirectory = fi2.DirectoryName
                        }
                    }.Start();
                    Info("回放文件已唤起!");
                }
                else
                {
                    Error("回放文件版本(" + v1 + ")与当前游戏版本(" + v2 + ")不一致!");
                }
                return;
            }

        }

        public static DateTime ToDateTime(long sjc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            DateTime dt = startTime.AddMilliseconds(sjc);
            return dt;
        }


        private static string GetAccessToken()
        {
            return lcu.GetAsync("/lol-league-session/v1/league-session-token").Result.Content.ReadAsStringAsync().Result.Replace("\"", "");
        }

        private static void FiddlerApplication_FiddlerDetach()
        {
            Info("FiddlerDetach");
        }

        private static void FiddlerApplication_BeforeRequest(Session oSession)
        {
            oSession.bBufferResponse = true;
            if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetSummonerInfo" || oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleList")
            {
                oSession.bBufferResponse = true;
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail")
            {
                oSession.bBufferResponse = true;
                var body = oSession.GetRequestBodyAsString();
                var gbd = body.JsonDeserialize<GetBattleDetail>();
                if (gbd.area != area)
                {
                    return;
                }
                long gameId = long.Parse(gbd.game_id);
                if (games.ContainsKey(gameId))
                {
                    oSession.utilCreateResponseAndBypassServer();
                    oSession.utilSetResponseBody(games[gameId]);
                    return;
                }
                gbd.id = "+AVQbMOJDz0z293IWeZkLQ==";
                gbd.account_type = 2;
                oSession.utilSetRequestBody(gbd.JsonSerialize());
            }
        }

        public static LCUHttpHelper lcu { get; set; }

        public static int area { get; set; }
        public static string currentPlatformId { get; set; }

        public static void InstallCertificate()
        {
            //生成证书
            CertMaker.createRootCert();
            //获取证书
            X509Certificate2 oRootcert = CertMaker.GetRootCertificate();

            //把证书安装到受信任的根证书颁发机构
            X509Store certStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            certStore.Open(OpenFlags.ReadWrite);
            try
            {
                certStore.Add(oRootcert);
            }
            finally
            {

                certStore.Close();
            }
            //证书赋值
            FiddlerApplication.oDefaultClientCertificate = oRootcert;
            //在解密HTTPS通信时，控制服务器证书错误是否被忽略。
            CONFIG.IgnoreServerCertErrors = true;

        }



        public static void Info(string log, bool newLine = true)
        {
            Log(log, "I", newLine);
        }

        public static void Error(string log, bool newLine = true)
        {
            var bf = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Log(log, "E", newLine);
            Console.ForegroundColor = bf;
        }


        public static void Log(string log, string level, bool newLine)
        {
            Console.Write(string.Format("{0} [{1}] {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), level, log));
            if (newLine)
            {
                Console.WriteLine();
            }
        }

        private static void FiddlerApplication_BeforeRespone(Session oSession)
        {
            if (!lcu.connect)
            {
                return;
            }
            if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetSummonerInfo")
            {
                var body = oSession.GetRequestBodyAsString();
                var gsi = body.JsonDeserialize<GetSummonerInfo>();
                if (gsi.area != area)
                {
                    return;
                }
                body = oSession.GetResponseBodyAsString();
                var gsir = body.JsonDeserialize<GetSummonerInfoResult>();
                if (gsir.result.error_code == 0)
                {
                    return;
                }
                else if (gsir.result.error_code == 8000021)
                {
                    body = oSession.GetRequestBodyAsString();
                    if (!openid.ContainsKey(gsi.id))
                    {
                        Error("unknow openid -> " + gsi.id);
                        Error("请重新查询对局或重新搜索该玩家");
                        return;
                    }
                    else
                    {
                        string name = openid[gsi.id];
                        Info("GetSummonerInfo -> " + name);
                        var content = lcu.GetAsync("/lol-summoner/v1/summoners/?name=" + name).Result;
                        var summoner = content.Content.ReadAsStringAsync().Result.JsonDeserialize<LcuSummons>();
                        if (player.ContainsKey(gsi.id))
                        {
                            player.Remove(gsi.id);
                        }
                        player.Add(gsi.id, summoner);
                        oSession.utilSetResponseBody(new
                        {
                            result = new
                            {
                                error_code = 0,
                                error_message = "success"
                            },
                            summoner = new
                            {
                                discredit = 0,
                                experience = 0,
                                ext = new
                                {
                                    lpl = ""
                                },
                                icon_id = summoner.profileIconId,
                                id = summoner.accountId,
                                level = summoner.summonerLevel,
                                name = summoner.displayName,
                                openid = gsi.id,
                                praise = 0,
                                top_of_canyon = false
                            }
                        }.JsonSerialize());
                    }
                }
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetTierRank")
            {
                var body = oSession.GetRequestBodyAsString();
                var gtr = body.JsonDeserialize<GetTierRank>();
                if (gtr.area != area)
                {
                    return;
                }
                body = oSession.GetResponseBodyAsString();
                var gtrr = body.JsonDeserialize<GetTierRankResult>();
                if (gtrr.result.error_code == 0)
                {
                    foreach (var item in gtrr.ranks)
                    {
                        if (!openid.ContainsKey(item.openid))
                        {
                            openid.Add(item.openid, item.name);
                        }
                    }
                }
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleReport")
            {
                var body = oSession.GetRequestBodyAsString();
                var gbr = body.JsonDeserialize<GetBattleReport>();
                body = oSession.GetResponseBodyAsString();
                var gbrr = body.JsonDeserialize<GetBattleReportResult>();
                if (gbr.area != area)
                {
                    return;
                }
                if (gbrr.result.error_code == 8000021)
                {
                    if (!player.ContainsKey(gbr.id))
                    {
                        Error("unknow openid -> " + gbr.id);
                        Error("请重新查询对局或重新搜索该玩家");
                        return;
                    }
                    var p = player[gbr.id];
                    var content = lcu.GetAsync("/lol-ranked/v1/ranked-stats/" + p.puuid).Result.Content.ReadAsStringAsync().Result;
                    var rs = content.JsonDeserialize<LcuRankedStats>();
                    var new_gbrr = new GetBattleReportResult()
                    {
                        battle_count = new GetBattleReportResult.Battle_Count(),
                        season_list = new List<Season_List>() {
                            new Season_List(){
                                sid = 17,
                                total = rs.queueMap.RANKED_SOLO_5x5.wins +  rs.queueMap.RANKED_SOLO_5x5.losses,
                                wins = rs.queueMap.RANKED_SOLO_5x5.wins,
                                losses = rs.queueMap.RANKED_SOLO_5x5.losses,
                                win_point = rs.queueMap.RANKED_SOLO_5x5.leaguePoints,
                                tier = GetTier(rs.queueMap.RANKED_SOLO_5x5.tier),
                                queue = GetQueue(rs.queueMap.RANKED_SOLO_5x5.division),
                                team_total = rs.queueMap.RANKED_FLEX_SR.wins + rs.queueMap.RANKED_FLEX_SR.losses,
                                team_wins = rs.queueMap.RANKED_FLEX_SR.wins,
                                team_losses =  rs.queueMap.RANKED_FLEX_SR.losses,
                                team_win_point = rs.queueMap.RANKED_FLEX_SR.leaguePoints,
                                team_tier = GetTier(rs.queueMap.RANKED_FLEX_SR.tier),
                                team_queue = GetQueue(rs.queueMap.RANKED_FLEX_SR.division)
                            }
                        },
                        result = new GetBattleReportResult.Result() { }
                    };
                    oSession.utilSetResponseBody(new_gbrr.JsonSerialize());
                }
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail")
            {
                var body = oSession.GetRequestBodyAsString();
                var gbd = body.JsonDeserialize<GetBattleDetail>();
                if (gbd.area != area)
                {
                    return;
                }
                body = oSession.GetResponseBodyAsString();
                var gbdr = body.JsonDeserialize<GetBattleDetailResult>();
                if (gbdr.result.error_code == 0)
                {
                    long gameId = long.Parse(gbdr.battle_detail.game_id);
                    if (!games.ContainsKey(gameId))
                    {
                        games.Add(gameId, body);
                    }
                    foreach (var item in gbdr.battle_detail.player_details)
                    {
                        if (!openid.ContainsKey(item.openid))
                        {
                            string name = HttpUtility.UrlDecode(item.name);
                            //Info("insert openid -> " + item.openid + "," + name);
                            openid.Add(item.openid, name);
                        }
                    }
                }
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleList")
            {
                var body = oSession.GetRequestBodyAsString();
                var gbl = body.JsonDeserialize<GetBattleList>();
                if (gbl.area != area)
                {
                    return;
                }
                body = oSession.GetResponseBodyAsString();
                var gblr = body.JsonDeserialize<GetBattleListResult>();
                if (gblr.result.error_code == 8000021)
                {
                    if (!player.ContainsKey(gbl.id))
                    {
                        Error("unknow openid -> " + gbl.id);
                        Error("请重新查询对局或重新搜索该玩家");
                        return;
                    }
                    var p = player[gbl.id];
                    var content = string.Empty;
                    bool usesgp = true;
                before:
                    {
                        string host = lcu.GetSgp(gbl.area);
                        if (host != null && usesgp)
                        {
                            try
                            {
                                WebClient web = new WebClient();
                                web.Encoding = Encoding.UTF8;
                                web.Headers.Add("Authorization", "Bearer " + GetAccessToken());
                                web.Headers.Add("Content-Type", "application/json");
                                content = web.DownloadString("https://" + host + "/match-history-query/v1/products/lol/player/" + p.puuid + "/SUMMARY?startIndex=" + gbl.offset + "&count=" + (gbl.count));
                                var match = content.JsonDeserialize<SgpMatchHistoryQuery>();
                                if (match.games == null)
                                {
                                    Error("not game");
                                    oSession.utilSetResponseBody(new GetBattleListResult()
                                    {
                                        battles = new List<Battle>(),
                                        result = new Do.Result()
                                    }.JsonSerialize());
                                }
                                else
                                {
                                    GetBattleListResult getBattleListResult = new GetBattleListResult()
                                    {
                                        battles = new List<Battle>(),
                                        result = new Do.Result()
                                    };
                                    List<Task> ts = new List<Task>();
                                    foreach (var item in match.games)
                                    {
                                        var participant = item.json.participants.FirstOrDefault(x => x.summonerName == p.displayName);
                                        if (queryMvp)
                                        {
                                            ts.Add(Task.Run(() =>
                                            {
                                                if (games.ContainsKey(item.json.gameId))
                                                {
                                                    content = games[item.json.gameId];
                                                }
                                                else
                                                {
                                                    var web2 = new WebClient();
                                                    web2.Headers.Add("Cookie", oSession.RequestHeaders["Cookie"]);
                                                    web2.Headers.Add("trpc-caller", "wegame.pallas.web.LolBattle");
                                                    web2.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                                                    web2.Headers.Add("Referer", "https://www.wegame.com.cn/helper/lol/v2/index.html");
                                                    web2.Encoding = Encoding.UTF8;
                                                    web2.Proxy = null;
                                                    content = web2.UploadString("https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail", new { account_type = 2, area, id = "+AVQbMOJDz0z293IWeZkLQ==", from_src = "lol_helper", game_id = item.json.gameId, api = "GetBattleDetail" }.JsonSerialize());
                                                }
                                                var gbdr = content.JsonDeserialize<GetBattleDetailResult>();
                                                if (gbdr.result.error_code == 0)
                                                {
                                                    if (!games.ContainsKey(item.json.gameId))
                                                    {
                                                        games.Add(item.json.gameId, content);
                                                    }
                                                }
                                                if (gbdr.battle_detail == null)
                                                {
                                                    //AddBattle(getBattleListResult, item, participant, new GetBattleDetailResult.Player_Details() { battleHonour = new GetBattleDetailResult.Battlehonour() });
                                                    return;
                                                }
                                                else
                                                {
                                                    var player = gbdr.battle_detail.player_details.Where(x => x.openid == gbl.id).FirstOrDefault();
                                                    foreach (var item2 in gbdr.battle_detail.player_details)
                                                    {
                                                        if (!openid.ContainsKey(item2.openid))
                                                        {
                                                            openid.Add(item2.openid, HttpUtility.UrlDecode(item2.name));
                                                        }
                                                    }
                                                    AddBattle(getBattleListResult, item, participant, player);
                                                }
                                            }));
                                        }
                                        else
                                        {
                                            AddBattle(getBattleListResult, item, participant, new GetBattleDetailResult.Player_Details() { battleHonour = new GetBattleDetailResult.Battlehonour() });
                                        }
                                    }
                                    Task.WaitAll(ts.ToArray());
                                    getBattleListResult.battles = getBattleListResult.battles.OrderByDescending(x => x.game_start_time).ToList();
                                    oSession.utilSetResponseBody(getBattleListResult.JsonSerialize());
                                }
                            }
                            catch (Exception ex)
                            {
                                Error("SGP接口异常->" + ex.Message);
                                usesgp = false;
                                goto before;
                            }
                        }
                        else
                        {
                            content = lcu.GetAsync("/lol-match-history/v1/products/lol/" + p.puuid + "/matches?begIndex=" + gbl.offset + "&endIndex=" + (gbl.offset + gbl.count)).Result.Content.ReadAsStringAsync().Result;
                            var match = content.JsonDeserialize<LcuMatchHistoryProductsResult>();
                            if (match.games == null)
                            {
                                Error("not game");
                                oSession.utilSetResponseBody(new GetBattleListResult()
                                {
                                    battles = new List<Battle>(),
                                    result = new Do.Result()
                                }.JsonSerialize());
                            }
                            else
                            {
                                GetBattleListResult getBattleListResult = new GetBattleListResult()
                                {
                                    battles = new List<Battle>(),
                                    result = new Do.Result()
                                };
                                List<Task> ts = new List<Task>();
                                foreach (var item in match.games.games)
                                {
                                    var participant = item.participants.FirstOrDefault();
                                    if (queryMvp)
                                    {
                                        ts.Add(Task.Run(() =>
                                        {
                                            if (games.ContainsKey(item.gameId))
                                            {
                                                content = games[item.gameId];
                                            }
                                            else
                                            {
                                                var web = new WebClient();
                                                web.Headers.Add("Cookie", oSession.RequestHeaders["Cookie"]);
                                                web.Headers.Add("trpc-caller", "wegame.pallas.web.LolBattle");
                                                web.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                                                web.Headers.Add("Referer", "https://www.wegame.com.cn/helper/lol/v2/index.html");
                                                web.Encoding = Encoding.UTF8;
                                                web.Proxy = null;
                                                content = web.UploadString("https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail", new { account_type = 2, area, id = "+AVQbMOJDz0z293IWeZkLQ==", from_src = "lol_helper", game_id = item.gameId, api = "GetBattleDetail" }.JsonSerialize());
                                            }
                                            var gbdr = content.JsonDeserialize<GetBattleDetailResult>();
                                            if (gbdr.battle_detail == null)
                                            {
                                                getBattleListResult.battles.Insert(0, new Battle()
                                                {
                                                    game_id = item.gameId.ToString(),
                                                    game_queue_id = item.queueId,
                                                    assists = participant.stats.assists,
                                                    kills = participant.stats.kills,
                                                    deaths = participant.stats.deaths,
                                                    position = participant.timeline.lane,
                                                    game_start_time = item.gameCreation.ToString(),
                                                    game_time_played = item.gameDuration,
                                                    win = participant.stats.win ? "Win" : "Lose",
                                                    champion_id = participant.championId,
                                                    double_kills = participant.stats.doubleKills,
                                                    triple_kills = participant.stats.tripleKills,
                                                    penta_kills = participant.stats.pentaKills,
                                                    map_id = item.mapId,
                                                });
                                            }
                                            else
                                            {
                                                if (gbdr.result.error_code == 0)
                                                {
                                                    if (!games.ContainsKey(item.gameId))
                                                    {
                                                        games.Add(item.gameId, content);
                                                    }
                                                }
                                                var player = gbdr.battle_detail.player_details.Where(x => x.openid == gbl.id).FirstOrDefault();
                                                getBattleListResult.battles.Insert(0, new Battle()
                                                {
                                                    game_id = item.gameId.ToString(),
                                                    game_queue_id = item.queueId,
                                                    assists = participant.stats.assists,
                                                    kills = participant.stats.kills,
                                                    deaths = participant.stats.deaths,
                                                    position = participant.timeline.lane,
                                                    game_start_time = item.gameCreation.ToString(),
                                                    game_time_played = item.gameDuration,
                                                    win = participant.stats.win ? "Win" : "Lose",
                                                    champion_id = participant.championId,
                                                    double_kills = participant.stats.doubleKills,
                                                    triple_kills = participant.stats.tripleKills,
                                                    penta_kills = participant.stats.pentaKills,
                                                    map_id = item.mapId,
                                                    was_mvp = player.battleHonour.isMvp,
                                                    was_svp = player.battleHonour.isSvp,
                                                });
                                            }
                                        }));
                                    }
                                    else
                                    {
                                        getBattleListResult.battles.Insert(0, new Battle()
                                        {
                                            game_id = item.gameId.ToString(),
                                            game_queue_id = item.queueId,
                                            assists = participant.stats.assists,
                                            kills = participant.stats.kills,
                                            deaths = participant.stats.deaths,
                                            position = participant.timeline.lane,
                                            game_start_time = item.gameCreation.ToString(),
                                            game_time_played = item.gameDuration,
                                            win = participant.stats.win ? "Win" : "Lose",
                                            champion_id = participant.championId,
                                            double_kills = participant.stats.doubleKills,
                                            triple_kills = participant.stats.tripleKills,
                                            penta_kills = participant.stats.pentaKills,
                                            map_id = item.mapId,
                                        });
                                    }
                                }
                                Task.WaitAll(ts.ToArray());
                                getBattleListResult.battles = getBattleListResult.battles.OrderByDescending(x => x.game_start_time).ToList();
                                oSession.utilSetResponseBody(getBattleListResult.JsonSerialize());
                            }
                        }
                    }
                }
                else
                {
                    Task.Run(() =>
                    {
                        try
                        {
                            foreach (var item in gblr.battles)
                            {
                                if (games.ContainsKey(long.Parse(item.game_id)))
                                {
                                    continue;
                                }
                                var web2 = new WebClient();
                                web2.Headers.Add("Cookie", oSession.RequestHeaders["Cookie"]);
                                web2.Headers.Add("trpc-caller", "wegame.pallas.web.LolBattle");
                                web2.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                                web2.Headers.Add("Referer", "https://www.wegame.com.cn/helper/lol/v2/index.html");
                                web2.Encoding = Encoding.UTF8;
                                web2.Proxy = null;
                                var content = web2.UploadString("https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail", new { account_type = 2, area, id = "+AVQbMOJDz0z293IWeZkLQ==", from_src = "lol_helper", game_id = item.game_id, api = "GetBattleDetail" }.JsonSerialize());
                                var gbdr = content.JsonDeserialize<GetBattleDetailResult>();
                                if (gbdr.result.error_code == 0)
                                {
                                    if (!games.ContainsKey(long.Parse(item.game_id)))
                                    {
                                        games.Add(long.Parse(item.game_id), content);
                                    }
                                }
                                var player = gbdr.battle_detail.player_details.Where(x => x.openid == gbl.id).FirstOrDefault();
                                foreach (var item2 in gbdr.battle_detail.player_details)
                                {
                                    if (!openid.ContainsKey(item2.openid))
                                    {
                                        openid.Add(item2.openid, HttpUtility.UrlDecode(item2.name));
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {

                        }
                    });

                }
            }
            else if (oSession.fullUrl == "https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/SearchPlayer")
            {
                var body = oSession.GetRequestBodyAsString();
                var sp = body.JsonDeserialize<SearchPlayer>();
                body = oSession.GetResponseBodyAsString();
                var spr = body.JsonDeserialize<SearchPlayerResult>();
                if (spr.result.error_code == 0)
                {
                    foreach (var item in spr.players)
                    {
                        if (item.area == area)
                        {
                            if (!openid.ContainsKey(item.openid))
                            {
                                openid.Add(item.openid, sp.nickname);
                            }
                        }
                    }
                }
            }
        }

        private static void AddBattle(GetBattleListResult getBattleListResult, SgpMatchHistoryQuery.Game item, SgpMatchHistoryQuery.Participant participant, GetBattleDetailResult.Player_Details player)
        {
            getBattleListResult.battles.Insert(0, new Battle()
            {
                game_id = item.json.gameId.ToString(),
                game_queue_id = item.json.queueId,
                assists = participant.assists,
                kills = participant.kills,
                deaths = participant.deaths,
                position = participant.lane,
                game_start_time = item.json.gameStartTimestamp.ToString(),
                game_time_played = item.json.gameDuration,
                win = participant.win ? "Win" : "Lose",
                champion_id = participant.championId,
                double_kills = participant.doubleKills,
                triple_kills = participant.tripleKills,
                penta_kills = participant.pentaKills,
                map_id = item.json.mapId,
                was_mvp = player.battleHonour.isMvp,
                was_svp = player.battleHonour.isSvp,
            });
        }

        public static int GetQueue(string queue)
        {
            switch (queue)
            {
                case "I": return 0;
                case "II": return 1;
                case "III": return 2;
                case "IV": return 3;
                default:
                    return 0;
            }

        }

        public static int GetTier(string tier)
        {
            switch (tier)
            {
                case "":
                case null:
                case "NONE": return 255;
                case "CHALLENGER": return 0;
                case "GRANDMASTER": return 7;
                case "MASTER": return 6;
                case "DIAMOND": return 1;
                case "PLATINUM": return 2;
                case "GOLD": return 3;
                case "SILVER": return 4;
                case "BRONZE": return 5;
                case "IRON": return 8;
                case "EMERALD": return 9;
                default: return -1;
            }
        }

        public static Dictionary<long, string> games { get; set; } = new Dictionary<long, string>();

        public static Dictionary<string, LcuSummons> player { get; set; } = new Dictionary<string, LcuSummons>();

        public static Dictionary<string, string> openid { get; set; } = new Dictionary<string, string>();

    }
}
